﻿//  Copyright (c) 2009 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace DNA.Mvc.UI
{
    /// <summary>
    /// Identity the action view result useing the specified master page.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class MasterLayoutAttribute : FilterAttribute, IResultFilter
    {
        private string _master = "";

        /// <summary>
        /// Gets/Sets the master page name
        /// </summary>
        public string MasterName
        {
            get { return _master; }
            set { _master = value; }
        }
        public MasterLayoutAttribute() { }

        public MasterLayoutAttribute(string masterName)
        {
            _master = masterName; 
        }


        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            string masterName = _master;
            var web = WebSiteContext.Current.Web;
            if (web != null)
            {
                if (string.IsNullOrEmpty(masterName))
                {
                    if (!string.IsNullOrEmpty(web.MasterName))
                        masterName = web.MasterName;
                }

                if (filterContext.Result is ViewResult)
                {
                    ViewResult result = filterContext.Result as ViewResult;
                    result.MasterName = masterName;
                }
            }
        }

        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
        }
    }
}
